<?php
namespace app\admin\controller;

use app\common\model\Page as PageModel;

class Template extends Admin 
{
	/**
	 * 模板列表
	 * @return array
	 */
	public function index(){
		$name = $this->request->param('name/s');
		$status = $this->request->param('status/d');

		$where = [];
		$map = [];
		$query = [];
		if(!empty($name)){
			$where[] = ['name','like','%'.$name.'%'];
			$query['name'] = $name;
		}				

		if(!empty($status)){
			$map['status'] = $status;
			$query['status'] = $status;
		}

		$list = PageModel::where($where)->where($map)->order('id desc')->paginate(15, false, ['query' => $query]);

		$this->assign('list',$list);
		return $this->fetch();
	}

	/**
	 * 新增模板
	 */
	public function add(){
		if($this->request->isPost()){
			$data = $this->request->post();

			//验证
			$result = $this->validate($data,[
				'name|名称' => 'require',	
				'data|内容' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);

			if($res = PageModel::create($data)){
				$this->success('新增成功');
			}else{
				$this->error('新增失败');
			}
		}else{
			$this->assign('info', null);

			return $this->fetch('edit');
		}
	}

	/**
	 * 编辑模板
	 * @param  integer $id
	 * @return mixed
	 */
	public function edit($id = 0){
		if($this->request->isPost()){
			$data = $this->request->post();

			//验证
			$result = $this->validate($data,[
				'name|名称' => 'require',	
				'data|内容' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);

			if($res = PageModel::update($data)){
				$this->success('编辑成功');
			}else{
				$this->error('编辑失败');
			}
		}else{
			empty($id) && $this->error('参数错误');

			$info = PageModel::where('id',$id)->find();
			$this->assign('info',$info);

			return $this->fetch();
		}
	}

	/**
	 * 删除页面
	 * @param  integer $id
	 * @return array
	 */
	public function del($id = 0){
		empty($id) && $this->error('参数错误');

		if(is_array($id)){
			$map[] = ['id','in',$id];
		}elseif(is_numeric($id)){
			$map[] = ['id','=',$id];
		}

		if($query = PageModel::where($map)->delete()){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}

	/**
	 * 更新状态
	 * @return mixed
	 */
	public function update(){
		$data = $this->request->param();

		if(empty($data)){
			$this->error('参数错误');
		}	
		
		if($query = PageModel::update($data)){
			$this->success('更新成功');
		}else{
			$this->error('更新失败');
		}
	}
}